# -*- coding:utf-8 -*-
"""
@Time : 2025/01/30 18:10 PM
@Author: xiaomi
@Des: 栏目列表
"""
from datetime import date
import os
import time

from app.common.common import write_access_log
from core.Response import success, fail, res_antd
from models.base import CateType, Category, ModelPage
from schemas.portal import category
from fastapi import HTTPException, Request, Query, APIRouter, Security, File, UploadFile
from config import settings
from typing import List
from tortoise.queryset import F
from core.Utils import get_cate_info

router = APIRouter(prefix='')

@router.get("",
            summary="栏目列表",
            # response_model=category.CategoryListData,
            )
async def cate_list():
    """
    获取所有栏目
    :return:
    """
    cate_data = await Category.all().order_by("-sort").values('cate_name', 'cate_id', 'cate_type', 'parent_id')
    cate_data = cate_tree(cate_data, 0)
    return success(data=cate_data)

def cate_tree(data, pid):
    """
    遍历栏目树
    :param data: cate[]
    :param parent_id: 父ID
    :return: list
    """
    result = []
    for item in data:
        if item["cate_type"] == -1:
            item['cate_link'] = "/portal/page/" + str(item["cate_id"]) + "/"
        if item["cate_type"] == 1:
            item['cate_link'] = "/portal/news/" + str(item["cate_id"]) + "/"
        if item["cate_type"] == 2:
            item['cate_link'] = "/portal/pro/" + str(item["cate_id"]) + "/"
        if item["cate_type"] == 3:
            item['cate_link'] = "/portal/job/" + str(item["cate_id"]) + "/"
        if pid == item["parent_id"]:
            temp = cate_tree(data, item["cate_id"])
            if len(temp) > 0:
                item["children"] = temp
            result.append(item)
    return result

@router.get("/page/{cate_id}",summary="栏目单页")
async def cate_page(cate_id: int):
    """
    获取栏目单页
    :param cate_id: 栏目ID
    :return:
    """
    # 1. 查询栏目基础信息
    category = await Category.filter(cate_id=cate_id).first()
    if not category:
        raise HTTPException(status_code=404, detail="栏目不存在")
    
    # 2. 验证栏目类型是否为单页
    if category.cate_type != CateType.SINGLE_PAGE:
        return fail(msg="该栏目不是单页类型")
    
    # 3. 获取关联的单页内容
    model_page = await ModelPage.filter(cate_id=cate_id).first()
    if not model_page:
        return fail(msg="单页内容未配置")
    
    # 4. 合并数据
    response_data = {
        "cate_name": category.cate_name,
        "cate_en_name": category.cate_en_name,
        "cate_desc": category.cate_desc,
        "content": model_page.content,
        "piclist": model_page.piclist
    }
    
    return success(data=response_data)


@router.get("/{cate_id}",summary="栏目详情")
async def cate_info(cate_id: int):
    cate_name = get_cate_info(cate_id, "name")
    return cate_name